import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/models/room.dart';
import 'package:awak/common/models/comment.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/common/repository/user_repository.dart';
import 'package:awak/common/repository/comment_repository.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

// 全局变量来传递房间数据
class RoomDataHolder {
  static Room? currentRoom;
}

class DetailRoomPage extends StatefulWidget {
  final Room? room;

  const DetailRoomPage({super.key, this.room});

  @override
  State<DetailRoomPage> createState() => _DetailRoomPageState();
}

class _DetailRoomPageState extends State<DetailRoomPage> {
  final TextEditingController _commentController = TextEditingController();
  final Map<int, User> _userCache = {}; // 缓存用户信息
  final CommentRepository _commentRepository = CommentRepository();
  final UserRepository _userRepository = UserRepository();

  // 缓存房间的评论数据
  Map<int, List<Comment>> _roomCommentsCache = {};
  Map<int, List<User>> _roomCommentersCache = {};

  @override
  void initState() {
    super.initState();
    // 获取当前房间的评论
    final currentRoom = widget.room ?? RoomDataHolder.currentRoom;
    if (currentRoom?.id != null) {
      context.read<AwakBloc>().add(FetchCommentsByRoomIdEvent(currentRoom!.id!));
      // 加载房间评论数据
      _loadRoomComments(currentRoom);
    }
    // 初始化用户缓存
    _initUserCache();
  }

  // 初始化用户缓存
  void _initUserCache() async {
    try {
      final userRepository = UserRepository();
      final users = await userRepository.getAllUsers();
      for (final user in users) {
        if (user.id != null) {
          _userCache[user.id!] = user;
        }
      }
      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      print('Error loading users: $e');
    }
  }

  // 获取房间的评论数据
  Future<void> _loadRoomComments(Room room) async {
    if (room.id == null) return;

    try {
      final comments = await _commentRepository.getCommentsByRoomId(room.id!);
      _roomCommentsCache[room.id!] = comments;

      // 获取评论者信息
      Set<int> userIds = comments.map((c) => c.userId).toSet();
      List<User> commenters = [];

      for (int userId in userIds) {
        final user = await _userRepository.getUserById(userId);
        if (user != null) {
          commenters.add(user);
        }
      }

      _roomCommentersCache[room.id!] = commenters;

      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      print('Error loading comments for room ${room.id}: $e');
    }
  }

  // 获取房间的评论数量
  int _getRoomCommentCount(Room room) {
    if (room.id == null) return 0;
    return _roomCommentsCache[room.id]?.length ?? 0;
  }

  // 获取房间的评论者头像列表
  List<User> _getRoomCommenters(Room room) {
    if (room.id == null) return [];
    return _roomCommentersCache[room.id] ?? [];
  }

  // 构建热度图标
  Widget _buildHotIcons(Room room, {double? iconSize}) {
    final commentCount = _getRoomCommentCount(room);

    // 根据评论数量决定显示几个火焰图标
    int fireCount = 0;
    if (commentCount >= 8) {
      fireCount = 3;
    } else if (commentCount >= 5) {
      fireCount = 2;
    } else if (commentCount >= 1) {
      fireCount = 1;
    }

    if (fireCount == 0) {
      return SizedBox.shrink();
    }

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(fireCount, (index) =>
        Icon(
          Icons.local_fire_department,
          color: Colors.orange,
          size: iconSize ?? 18.w,
        ),
      ),
    );
  }

  // 构建评论者头像组件
  Widget _buildCommentersAvatars(Room room) {
    final commenters = _getRoomCommenters(room);

    if (commenters.isEmpty) {
      return Row(
        children: List.generate(3, (index) =>
          Padding(
            padding: EdgeInsets.only(right: 2.w),
            child: CircleAvatar(
              radius: 10.w,
              backgroundColor: Colors.grey.withValues(alpha: 0.3),
              child: Icon(Icons.person, size: 12.w, color: Colors.grey),
            ),
          ),
        ),
      );
    }

    List<Widget> avatars = [];

    if (commenters.length <= 3) {
      // 如果评论者不超过3个，显示所有头像
      for (int i = 0; i < commenters.length; i++) {
        avatars.add(
          Padding(
            padding: EdgeInsets.only(right: 2.w),
            child: CircleAvatar(
              radius: 10.w,
              backgroundImage: AssetImage(commenters[i].avatar ?? AwakImages.avatar),
            ),
          ),
        );
      }
      // 如果不足3个，用默认头像补齐
      for (int i = commenters.length; i < 3; i++) {
        avatars.add(
          Padding(
            padding: EdgeInsets.only(right: 2.w),
            child: CircleAvatar(
              radius: 10.w,
              backgroundColor: Colors.grey.withValues(alpha: 0.3),
              child: Icon(Icons.person, size: 12.w, color: Colors.grey),
            ),
          ),
        );
      }
    } else {
      // 如果超过3个评论者，只显示前2个头像，然后显示 "+数字"
      for (int i = 0; i < 2; i++) {
        avatars.add(
          Padding(
            padding: EdgeInsets.only(right: 2.w),
            child: CircleAvatar(
              radius: 10.w,
              backgroundImage: AssetImage(commenters[i].avatar ?? AwakImages.avatar),
            ),
          ),
        );
      }

      // 添加 +数字 显示
      avatars.add(
        Padding(
          padding: EdgeInsets.only(right: 2.w),
          child: CircleAvatar(
            radius: 10.w,
            backgroundColor: Colors.black,
            child: Text(
              '+${commenters.length - 2}',
              style: TextStyle(
                color: Colors.white,
                fontSize: 8.sp,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      );
    }

    return Row(children: avatars);
  }

  // 获取当前房间评论最多的用户
  User? _getTopCommenterUser(Room room) {
    if (room.id == null) return null;

    final comments = _roomCommentsCache[room.id] ?? [];
    if (comments.isEmpty) return null;

    // 统计每个用户的评论数量
    Map<int, int> userCommentCounts = {};
    for (final comment in comments) {
      userCommentCounts[comment.userId] = (userCommentCounts[comment.userId] ?? 0) + 1;
    }

    // 获取当前登录用户ID（这里需要从认证状态获取）
    // 暂时假设当前用户ID为1，实际应该从BlocProvider获取
    int? currentUserId = 1; // TODO: 从认证状态获取真实的当前用户ID

    // 移除当前用户
    userCommentCounts.remove(currentUserId);

    if (userCommentCounts.isEmpty) return null;

    // 找到评论最多的用户ID
    int topUserId = userCommentCounts.entries
        .reduce((a, b) => a.value > b.value ? a : b)
        .key;

    // 从缓存中获取用户信息
    return _userCache[topUserId];
  }

  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 使用传递的参数或全局变量
    final currentRoom = widget.room ?? RoomDataHolder.currentRoom;

    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFFD7F349), Color(0xFFFFFABA)],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
            child: SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: 12.w,
                      vertical: 16.h,
                    ),
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        Align(
                          alignment: Alignment.centerLeft,
                          child: GestureDetector(
                            onTap: () => Beamer.of(context).beamBack(),
                            child: Icon(AwakSvg.back),
                          ),
                        ),
                        Center(
                          child: Text(
                            'DISCUSS ROOM DETAILS',
                            style: AwakText.titleStyle,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 24.w),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(12.r),
                          child: Image.asset(
                            currentRoom?.roomAvatar ?? AwakImages.learning1,
                            width: 120.w,
                            height: 120.h,
                            fit: BoxFit.cover,
                          ),
                        ),
                        SizedBox(width: 16.w),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(height: 4.h),
                              Text(
                                currentRoom?.roomName ?? 'Chatting About Learning Methods',
                                style: AwakText.body16Style.copyWith(
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                              SizedBox(height: 12.h),
                              // Participant Count 换行
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    'Participant Count:',
                                    style: AwakText.body14Style.copyWith(
                                      color: Colors.black.withValues(alpha: 0.6),
                                      fontWeight: FontWeight.w400,
                                      fontSize: 12.sp,
                                    ),
                                  ),
                                  SizedBox(height: 8.h),
                                  Builder(
                                    builder: (context) {
                                      final currentRoom = widget.room ?? RoomDataHolder.currentRoom;
                                      if (currentRoom == null) {
                                        return Row(
                                          children: [
                                            ...List.generate(3, (i) =>
                                              Padding(
                                                padding: EdgeInsets.only(right: 2.w),
                                                child: CircleAvatar(
                                                  radius: 10.w,
                                                  backgroundColor: Colors.grey.withValues(alpha: 0.3),
                                                  child: Icon(Icons.person, size: 12.w, color: Colors.grey),
                                                ),
                                              ),
                                            ),
                                            SizedBox(width: 4.w),
                                            Text(
                                              '0 People',
                                              style: AwakText.body14Style.copyWith(
                                                color: Colors.black,
                                                fontWeight: FontWeight.w400,
                                                fontSize: 12.sp,
                                              ),
                                            ),
                                          ],
                                        );
                                      }

                                      final commentCount = _getRoomCommentCount(currentRoom);

                                      return Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            children: [
                                              _buildCommentersAvatars(currentRoom),
                                              SizedBox(width: 4.w),
                                              Text(
                                                '$commentCount People',
                                                style: AwakText.body14Style.copyWith(
                                                  color: Colors.black,
                                                  fontWeight: FontWeight.w400,
                                                  fontSize: 12.sp,
                                                ),
                                              ),
                                              Spacer(),
                                              _buildHotIcons(currentRoom, iconSize: 18.w),
                                            ],
                                          ),
                                        ],
                                      );
                                    },
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 18.h),
                  // Private String Owner
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 18.w),
                    child: Text(
                      'Private String Owner',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 18.w),
                    child: Container(
                      decoration: BoxDecoration(
                        color: const Color(0xFFD3F427),
                        borderRadius: BorderRadius.circular(16.r),
                        border: Border.all(color: Colors.black, width: 2.w),
                      ),
                      child: Row(
                        children: [
                          SizedBox(width: 8.w),
                          Container(
                            margin: EdgeInsets.only(top: 8.h, bottom: 8.h),
                            width: 12.w,
                            height: 74.h,
                            decoration: BoxDecoration(
                              color: const Color(0xFFFEF463),
                              borderRadius: BorderRadius.circular(16.r),
                              border: Border.all(
                                color: Colors.black,
                                width: 2.w,
                              ),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.all(10.w),
                            child: Builder(
                              builder: (context) {
                                final currentRoom = widget.room ?? RoomDataHolder.currentRoom;
                                final topCommenter = currentRoom != null ? _getTopCommenterUser(currentRoom) : null;

                                return CircleAvatar(
                                  radius: 24.w,
                                  backgroundImage: AssetImage(
                                    topCommenter?.avatar ?? AwakImages.avatar,
                                  ),
                                );
                              },
                            ),
                          ),
                          Expanded(
                            child: Padding(
                              padding: EdgeInsets.symmetric(vertical: 12.h),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Builder(
                                    builder: (context) {
                                      final currentRoom = widget.room ?? RoomDataHolder.currentRoom;
                                      final topCommenter = currentRoom != null ? _getTopCommenterUser(currentRoom) : null;

                                      return Text(
                                        topCommenter?.nickname ?? 'No Active User',
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: 16.sp,
                                        ),
                                      );
                                    },
                                  ),
                                  SizedBox(height: 4.h),
                                  Builder(
                                    builder: (context) {
                                      final currentRoom = widget.room ?? RoomDataHolder.currentRoom;
                                      final topCommenter = currentRoom != null ? _getTopCommenterUser(currentRoom) : null;

                                      return Text(
                                    topCommenter?.signature ?? 'No signature',
                                    style: TextStyle(
                                      fontSize: 13.sp,
                                      color: Colors.black.withValues(alpha: 0.7),
                                    ),
                                      );
                                    },
                                  ),
                                ],
                              ),
                            ),
                          ),
                          SizedBox(width: 12.w),
                          Column(
                            children: [
                              Icon(AwakSvg.follow, size: 22.w),
                              SizedBox(height: 12.h),
                              Icon(AwakSvg.chat, size: 22.w),
                            ],
                          ),
                          SizedBox(width: 12.w),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 18.h),
                  // Viewpoint
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 18.w),
                    child: Text(
                      'Viewpoint',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 18.w),
                    child: Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        color: const Color(0xFFF0F44A),
                        borderRadius: BorderRadius.circular(16.r),
                        border: Border.all(color: Colors.black, width: 2.w),
                      ),
                      padding: EdgeInsets.all(16.w),
                      child: Text(
                        currentRoom?.viewPoint ?? 'My Own Years Of Learning Experience Tell Me That Only By Working Hard Can One Find A Way Out.',
                        style: AwakText.body16Style.copyWith(
                          fontWeight: FontWeight.w600,
                          height: 1.5,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 18.h),
                  // Learning Exchange 标题
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 18.w),
                    child: Text(
                      'Learning Exchange',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                  SizedBox(height: 12.h),
                  // 评论区
                  Expanded(
                    child: BlocBuilder<AwakBloc, AwakState>(
                      buildWhen: (previous, current) {
                        // 只在评论相关的状态变化时重建
                        return current is CommentLoading ||
                               current is CommentsLoaded ||
                               current is CommentFailure ||
                               current is CommentSuccess;
                      },
                      builder: (context, state) {
                        if (state is CommentLoading) {
                          return const Center(child: CircularProgressIndicator());
                        } else if (state is CommentsLoaded) {
                          return _buildCommentsList(state.comments);
                        } else if (state is CommentFailure) {
                          return Center(child: Text(state.message));
                        } else {
                          return _buildCommentsList([]);
                        }
                      },
                    ),
                  ),
                  SizedBox(height: 80.h), // 给底部输入框留空间
                ],
              ),
            ),
          ),
          // 底部发送框
          Positioned(
            left: 0,
            right: 0,
            bottom: 40.h,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 12.w),
              child: Row(
                children: [
                  Expanded(
                    child: Container(
                      height: 44.h,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12.r),
                        border: Border.all(color: Colors.black, width: 2.w),
                      ),
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
                      child: TextField(
                        controller: _commentController,
                        decoration: InputDecoration(
                          hintText: 'Send A Message',
                          hintStyle: AwakText.body16Style.copyWith(
                            color: const Color(0xFFCDCDCD),
                            fontWeight: FontWeight.w600,
                          ),
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 8.w),
                  GestureDetector(
                    onTap: _sendComment,
                    child: Container(
                      height: 44.h,
                      padding: EdgeInsets.symmetric(horizontal: 18.w),
                      decoration: BoxDecoration(
                        color: Colors.black,
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: Center(
                        child: Text(
                          'Send',
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 16.sp,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建评论列表
  Widget _buildCommentsList(List<Comment> comments) {
    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 18.w),
      itemCount: comments.length,
      itemBuilder: (context, index) {
        final comment = comments[index];
        return _buildCommentItem(comment);
      },
    );
  }

  // 构建单个评论项
  Widget _buildCommentItem(Comment comment) {
    // 获取用户信息
    final user = _getUserInfo(comment.userId);

    return Container(
          margin: EdgeInsets.only(bottom: 20.h),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CircleAvatar(
                radius: 20.w,
                backgroundImage: AssetImage(user.avatar ?? AwakImages.avatar1),
              ),
              SizedBox(width: 10.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 2.h),
                    Text(
                      user.nickname ?? 'Unknown User',
                      style: AwakText.body16Style,
                    ),
                    Text(
                      user.signature ?? '',
                      style: AwakText.body14Style.copyWith(
                        color: Colors.black.withValues(alpha: 0.6),
                        fontWeight: FontWeight.w400,
                        fontSize: 12.sp,
                      ),
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      comment.content,
                      style: AwakText.body16Style.copyWith(
                        fontWeight: FontWeight.w600,
                        height: 1.5,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(width: 8.w),
              Icon(AwakSvg.report, size: 22.w),
            ],
          ),
        );
  }

  // 获取用户信息
  User _getUserInfo(int userId) {
    // 从缓存中获取用户数据
    if (_userCache.containsKey(userId)) {
      return _userCache[userId]!;
    }

    // 如果缓存中没有，返回一个占位用户
    return User(
      id: userId,
      username: 'user$userId',
      password: '',
      nickname: 'Unknown User',
      avatar: AwakImages.avatar1,
      signature: 'User not found',
    );
  }

  // 发送评论
  void _sendComment() {
    final content = _commentController.text.trim();
    if (content.isEmpty) return;

    final currentRoom = widget.room ?? RoomDataHolder.currentRoom;
    if (currentRoom?.id == null) return;

    // 获取当前登录用户ID
    final currentUserId = _getCurrentUserId();
    if (currentUserId == null) return;

    // 创建新评论
    final comment = Comment(
      content: content,
      userId: currentUserId,
      roomId: currentRoom!.id!,
    );

    // 发送评论
    context.read<AwakBloc>().add(AddCommentEvent(comment));

    // 清空输入框
    _commentController.clear();
  }

  // 获取当前登录用户ID
  int? _getCurrentUserId() {
    // 从 Bloc 状态中获取当前用户
    final state = context.read<AwakBloc>().state;
    if (state is AwakSuccess) {
      return state.user.id;
    }
    // 如果没有登录用户，默认返回用户1的ID
    return 1;
  }
}
